#!/bin/bash

if [ $# -lt 1 ]
then
  echo "Usage: $0 [mysql|python|js]"
  exit
fi

MYSQL="mysql"
ECMA="ecma"
PYTHON="python"

case "$1" in
 $MYSQL) echo "Selected MySQL parser"
 SOURCE_FILE=MySQL.g
 SOURCE_FILE2=MySQLSimpleParser.g
 ;;
 *) echo "Unknown parser type $1"
 exit 1
 ;;
esac

if [ -z "$SOURCE_FILE" ]
then
  echo "Source file is not implemented"
  exit 1
fi

TARGET_DIRECTORY=..
GENERATE_FILES=false
BASE_DIRECTORY=../../../..
LINUX_RES_JAR_PATH=$BASE_DIRECTORY/linux-res/bin/antlr-3.4-complete.jar

if [ $1 = $MYSQL ]; then
  if [ ! -f "$TARGET_DIRECTORY/MySQLLexer.c" ]  || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLLexer.c" ];  then GENERATE_FILES=true; fi
  if [ ! -f "$TARGET_DIRECTORY/MySQLLexer.h" ]  || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLLexer.h" ];  then GENERATE_FILES=true; fi
  if [ ! -f "$TARGET_DIRECTORY/MySQLParser.c" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLParser.c" ]; then GENERATE_FILES=true; fi
  if [ ! -f "$TARGET_DIRECTORY/MySQLParser.h" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLParser.h" ]; then GENERATE_FILES=true; fi
  if [ ! -f "$TARGET_DIRECTORY/MySQLSimpleParser.c" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLSimpleParser.c" ]; then GENERATE_FILES=true; fi
  if [ ! -f "$TARGET_DIRECTORY/MySQLSimpleParser.h" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLSimpleParser.h" ]; then GENERATE_FILES=true; fi
fi

if [ $GENERATE_FILES == true ]; then
  # Check if the supplied file exists
  if [ ! -f "$ANTLR_JAR_PATH" ]; then
    # Check the default development path
    if [ -f "$LINUX_RES_JAR_PATH" ]; then
      ANTLR_JAR_PATH="$LINUX_RES_JAR_PATH"
    else
      echo "The antlr-3.4-complete.jar file could not be found."
      echo "Please make sure that linux-res is in `cd $BASE_DIRECTORY; pwd` or add the ANTLR_JAR_PATH enviroment variable with the path to the file."
      echo "You'll also need Java Runtime Enviroment installed, so the parser files can be regenerated."
      exit 1
    fi
  fi

  java -Xmx1024m -jar "$ANTLR_JAR_PATH" -make $SOURCE_FILE -o $TARGET_DIRECTORY -Xmaxswitchcaselabels 30
  if [ -n "$SOURCE_FILE2" ]; then
    java -Xmx1024m -jar "$ANTLR_JAR_PATH" -make $SOURCE_FILE2 -o $TARGET_DIRECTORY -Xmaxswitchcaselabels 30
  fi
fi

